from django.shortcuts import render,redirect,HttpResponse
from django.contrib.auth import login,authenticate,logout
from django.contrib.auth.decorators import login_required
from django.http import QueryDict
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from django import forms
from django.forms import widgets as ws
from django.forms import fields as fs
import json,re,datetime
from django.conf import settings
from web import models
asset_url_list=['/asset/','/new_asset/','/discard_asset/'] #资产管理相关url，用于判断是否展开子菜单
# Create your views here.
@login_required
def summary(request):
    if request.method == 'DELETE':
        envent_id=QueryDict(request.body).get('envent_id')
        physical_id=QueryDict(request.body).get('physical_id')
        print(physical_id)
        if envent_id:
            models.Asset_status.objects.filter(id=envent_id).delete()
        if physical_id:
            physical_type=QueryDict(request.body).get('physical_type')
            print('type',physical_type)
            if physical_type=='1':#disk
                models.Disk.objects.filter(id=physical_id).delete()
                models.Asset_status.objects.filter(id=envent_id).delete()
            if physical_type=='2':
                models.Memory.objects.filter(id=physical_id).delete()
                models.Asset_status.objects.filter(id=envent_id).delete()
            if physical_type=='3':
                models.Asset_status.objects.filter(id=envent_id).delete()
                models.Nic.objects.filter(id=physical_id).delete()
        return HttpResponse('666')
    #获取离线客户端
    yesterday_time=datetime.datetime.now()+ datetime.timedelta(-2)
    offline_asset=models.Asset.objects.filter(report_time__lte=yesterday_time).all()
    for Asset in offline_asset:
        if not models.Asset_status.objects.filter(asset=Asset,asset_status=1):#如果已存在离线记录则不再重复记录
            online_status=models.Asset_status.objects.filter(asset=Asset,asset_status=0)
            if online_status:
                online_status.update(content='客户端状态离线！',asset_status=1)
            else:
                models.Asset_status.objects.create(asset=Asset,asset_status=1,content='客户端状态离线！')

    Status=request.GET.get('status')
    query_string=request.environ.get('QUERY_STRING')
    obj=models.Asset_status.objects.filter(asset_status=Status).all()
    if Status:
        return render(request,'info_detail.html',{'obj':obj,'query_string':query_string})
    all_asset=models.Asset.objects.count()
    discard_asset=models.Discard_server.objects.all().count()
    new_asset=models.Server.objects.filter(asset_id=None).all().count()
    offline_asset=models.Asset_status.objects.filter(asset_status=1).values('asset_id').distinct().count()
    update_asset=models.Asset_status.objects.filter(asset_status=2).count()
    lose_asset=models.Asset_status.objects.filter(asset_status=3).count()
    return render(request,'summary.html',{
            'all_asset':all_asset,
            'discard_asset':discard_asset,
            'new_asset':new_asset,
            'offline_asset':offline_asset,
            'update_asset':update_asset,
            'lose_asset':lose_asset,

                                            })

detail_asset_id=None
@login_required
def asset(request):
    global asset_url_list,detail_asset_id
    args=request.environ.get('QUERY_STRING')  #获取跳转过来之前的页码，客户查看资源详情后可以回到之前的页面去
    class addAssetMD(forms.ModelForm):
        class Meta:
            model=models.Asset
            exclude=('create_time','asset_status','update_time','type','server')
            labels={
                'type':'资产类型',
                'idc':'数据中心',
                'tag':'资产标签',
                'businessunit':'业务线',
                'cabinet_order':'机柜中位置',
            }

            error_messages={
                'cabinet_order':{
                    'unique':'该机架已经放置了其他设备，请输入其他空闲机架！！',
                }
            }
            widgets={
                'type':fs.TextInput(attrs={"class":"form-control input-sm",'disabled':'disabled'}),
                'idc':fs.Select(attrs={"class":"form-control input-sm"}),
                'tag':fs.Select(attrs={"class":"form-control input-sm"}),
                'businessunit':fs.Select(attrs={"class":"form-control input-sm"}),
                'cabinet_order':fs.TextInput(attrs={"class":"form-control input-sm"})

            }

    search_text=request.GET.get('search_text')
    search_field=request.GET.get('search_field')

    if request.method == 'DELETE':
        delete_asset_id=json.loads(QueryDict(request.body).get('host_list'))
        for asset_id in delete_asset_id:
            if asset_id is None:
                continue
            del_asset_obj=models.Asset.objects.filter(id=asset_id).first()
            models.Audit_log.objects.create(user=request.user,content='删除机柜号%s中的设备！'%del_asset_obj.cabinet_order)
            models.Asset.objects.filter(id=asset_id).delete()

        return HttpResponse('666')
    elif request.method == 'GET':

        #获取资产详情
        if request.GET.get('detail_asset_id'):
            detail_asset_id=request.GET.get('detail_asset_id')
            args=request.GET.get('args')
            asset_detail=models.Asset.objects.get(id=request.GET.get('detail_asset_id'))
            server_obj=models.Asset.objects.filter(id=request.GET.get('detail_asset_id')).first() #asset_obj,不是server_obj，难得改了...................
            log_obj= models.asset_change_log.objects.filter(server_id=server_obj.server.id).order_by('-change_date')
            print(server_obj)
            print('log_obj',log_obj)
            obj=addAssetMD(instance=server_obj)
            disk_detail=models.Disk.objects.filter(server__asset_id=asset_detail.id)
            mem_detail=models.Memory.objects.filter(server__asset_id=asset_detail.id)
            nic_detail=models.Nic.objects.filter(server__asset_id=asset_detail.id)

        if not search_field:
            all_asset=models.Asset.objects.all()
        else:
            if search_field == 'asset_status':
                if re.search('正常',search_text.strip()):
                    all_asset=models.Asset.objects.filter(asset_status=0).all()
                if re.search('离线',search_text.strip()):
                    all_asset=models.Asset.objects.filter(asset_status=1).all()
            if search_field == 'manage_ipv4':
                all_asset=models.Asset.objects.filter(Server__manage_ipv4__iregex=search_text).all()
            if search_field == 'model':
                all_asset=models.Asset.objects.filter(Server__model__iregex=search_text).all()
            if search_field == 'manufacturer':
                all_asset=models.Asset.objects.filter(Server__manufacturer__iregex=search_text).all()
            if search_field =='businessunit':
                all_asset=models.Asset.objects.filter(businessunit__name__iregex=search_text).all()

        paginator=Paginator(all_asset,settings.WEB_PEER_PAGE)
        page = request.GET.get('page')
        try:
            contacts = paginator.page(page)
        except PageNotAnInteger:
            # 如果page不是一个整数，则展示第一页。
            contacts = paginator.page(1)
        except EmptyPage:
            # 如果page不在范围内（例如，9999），则展示结果的最后一页。
            contacts = paginator.page(paginator.num_pages)
        if request.GET.get('detail_asset_id'):#用户获取资产详情
            return render(request,'asset.html',{'all_asset':contacts,
                                        'asset_url':asset_url_list,
                                        'search_field':search_field,
                                        'search_text':search_text,
                                        'asset_count':all_asset.count(),
                                        'asset_detail':asset_detail,
                                        'disk_detail':disk_detail,
                                        'mem_detail':mem_detail,
                                        'nic_detail':nic_detail,
                                        'show_detail':True,
                                        'args':args,
                                        'obj':obj,  #当前资产obj
                                        'log_obj':log_obj
                                        })


        return render(request,'asset.html',{'all_asset':contacts,
                                            'asset_url':asset_url_list,
                                            'search_field':search_field,
                                            'search_text':search_text,
                                            'asset_count':all_asset.count(),
                                            'show_detail':False,
                                            'args':args
                                            })
    elif request.method=='POST':
        obj=addAssetMD(instance=models.Asset.objects.filter(id=detail_asset_id).first(),data=request.POST)
        if obj.is_valid():
            models.Audit_log.objects.create(user=request.user,content='修改资产信息！%s'%obj.cleaned_data)
            obj.save()

            return redirect('asset/?detail_asset_id=%s'%detail_asset_id)
        else:
            # print(obj.errors.as_json())
            asset_detail=models.Asset.objects.get(id=request.GET.get('detail_asset_id'))
            disk_detail=models.Disk.objects.filter(server__asset_id=asset_detail.id)
            mem_detail=models.Memory.objects.filter(server__asset_id=asset_detail.id)
            nic_detail=models.Nic.objects.filter(server__asset_id=asset_detail.id)
            return render(request,'asset.html',{
                                        'asset_url':asset_url_list,
                                        'search_field':search_field,
                                        'search_text':search_text,
                                        'asset_count':models.Asset.objects.all().count(),
                                        'asset_detail':asset_detail,
                                        'disk_detail':disk_detail,
                                        'mem_detail':mem_detail,
                                        'nic_detail':nic_detail,
                                        'show_detail':True,
                                        'args':args,
                                        'obj':obj,  #当前资产obj
                                        'form_error':True,#有错误产生，将面板修改页设为ACTIVE
                                        })

@login_required
def idc_mgr(request):
    class addidc(forms.ModelForm):
        class Meta:
            model=models.Idc
            fields='__all__'
            labels={
                'name':'机房名称',
                'position':'机房位置'
            }

            error_messages={
                'name':{
                    'unique':'此机房名称已存在！！！',
                }
            }
            widgets={
                'name':fs.TextInput(attrs={"class":"form-control input-sm"}),
                'position':fs.TextInput(attrs={"class":"form-control input-sm"}),
            }
    idc_obj=models.Idc.objects.all()
    if request.method=='GET':
        # all_idc_obj=models.Idc.objects.all()
        obj=addidc()

        return render(request,'idc_mgr.html',{'obj':obj,'idc_obj':idc_obj})
    elif request.method=='POST':
        obj=addidc(request.POST)
        if obj.is_valid():
            obj.save()
            return redirect('/idc_mgr/')
        else:
            return render(request,'idc_mgr.html',{'obj':obj,'idc_obj':idc_obj})
    elif request.method=='DELETE':
        try:
            idc_id=QueryDict(request.body).get('idc_id')
            models.Audit_log.objects.create(user=request.user,content='删除机房:%s'%models.Idc.objects.filter(id=idc_id).first().name)
            models.Idc.objects.filter(id=idc_id).delete()
            return HttpResponse(0)
        except Exception as e:
            return HttpResponse(1)

@login_required
def tag_mgr(request):
    class addtag(forms.ModelForm):
        class Meta:
            model=models.Tag
            fields='__all__'
            labels={
                'name':'标签名称',
            }

            error_messages={
                'name':{
                    'unique':'此标签名称已存在！！！',
                }
            }
            widgets={
                'name':fs.TextInput(attrs={"class":"form-control input-sm"}),
            }
    tag_obj=models.Tag.objects.all()
    if request.method=='GET':
        obj=addtag()

        return render(request,'tag_mgr.html',{'obj':obj,'tag_obj':tag_obj})
    elif request.method=='POST':
        obj=addtag(request.POST)
        if obj.is_valid():
            obj.save()
            return redirect('/tag_mgr/')
        else:
            return render(request,'tag_mgr.html',{'obj':obj,'tag_obj':tag_obj})
    elif request.method=='DELETE':
        try:
            tag_id=QueryDict(request.body).get('tag_id')
            models.Audit_log.objects.create(user=request.user,content='删除机房:%s'%models.Tag.objects.filter(id=tag_id).first().name)
            models.Tag.objects.filter(id=tag_id).delete()
            return HttpResponse(0)
        except Exception as e:
            return HttpResponse(1)
@login_required
def business_mgr(request):
    class addbs(forms.ModelForm):
        class Meta:
            model=models.BusinessUnit
            fields='__all__'
            labels={
                'name':'业务线名称',
                'administrator_name':'管理员姓名',
                'administrator_phone':'管理员电话'
            }

            error_messages={
                'name':{
                    'unique':'此业务线名称已存在！！！',
                }
            }
            widgets={
                'name':fs.TextInput(attrs={"class":"form-control input-sm"}),
                'administrator_name':fs.TextInput(attrs={"class":"form-control input-sm"}),
                'administrator_phone':fs.TextInput(attrs={"class":"form-control input-sm"}),
            }
    bs_obj=models.BusinessUnit.objects.all()
    if request.method=='GET':
        obj=addbs()

        return render(request,'business_mgr.html',{'bs_obj':bs_obj,'obj':obj})
    elif request.method=='POST':
        obj=addbs(request.POST)
        if obj.is_valid():
            obj.save()
            return redirect('/business_mgr/')
        else:
            return render(request,'business_mgr.html',{'obj':obj,'bs_obj':bs_obj})
    elif request.method=='DELETE':
        try:
            bs_id=QueryDict(request.body).get('bs_id')
            models.Audit_log.objects.create(user=request.user,content='删除机房:%s'%models.BusinessUnit.objects.filter(id=bs_id).first().name)
            models.BusinessUnit.objects.filter(id=bs_id).delete()
            return HttpResponse(0)
        except Exception as e:
            return HttpResponse(1)
@login_required
def discard(request):
    global asset_url_list
    if request.method=='DELETE':
        server_id=QueryDict(request.body).get('server_id')
        models.Audit_log.objects.create(user=request.user,content='将ip地址为:%s的资产设为合法！！'%models.Discard_server.objects.filter(id=server_id).first().manage_ipv4)

        models.Discard_server.objects.filter(id=server_id).delete()
        return HttpResponse('666')
    elif request.method=='GET':
        if request.GET.get('ip'):
            discard_server=models.Discard_server.objects.filter(manage_ipv4=request.GET.get('ip'))
        else:
            discard_server=models.Discard_server.objects.all()
        paginator=Paginator(discard_server,settings.WEB_PEER_PAGE)
        page = request.GET.get('page')
        try:
            contacts = paginator.page(page)
        except PageNotAnInteger:
            # 如果page不是一个整数，则展示第一页。
            contacts = paginator.page(1)
        except EmptyPage:
            # 如果page不在范围内（例如，9999），则展示结果的最后一页。
            contacts = paginator.page(paginator.num_pages)
        return render(request,'discard_asset.html',{'all_asset':contacts,'asset_url':asset_url_list,'discard_asset_count':discard_server.count()})


Server_id=None
@login_required
def new_asset(request):
    global Server_id,asset_url_list
    class addAssetMD(forms.ModelForm):
        class Meta:
            model=models.Asset
            exclude=('create_time','asset_status','update_time','report_time')
            labels={
                'type':'资产类型',
                'idc':'数据中心',
                'tag':'资产标签',
                'businessunit':'业务线',
                'cabinet_order':'机柜位置',


            }
            error_messages={
                'cabinet_order':{
                    'unique':'该机架已经放置了其他设备，请输入其他空闲机架！！',
                }}

            widgets={
                'type':fs.TextInput(attrs={"class":"form-control input-sm",'disabled':'disabled'}),
                'idc':fs.Select(attrs={"class":"form-control input-sm"}),
                'tag':fs.Select(attrs={"class":"form-control input-sm"}),
                'businessunit':fs.Select(attrs={"class":"form-control input-sm"}),
                'cabinet_order':fs.TextInput(attrs={"class":"form-control input-sm"}),
                'server':fs.TextInput(attrs={"class":"form-control input-sm",'disabled':'disabled','style':'display: none'})

            }
    if request.GET.get('ip'):
        new_server=models.Server.objects.filter(manage_ipv4=request.GET.get('ip'))
    else:
        new_server=models.Server.objects.filter(asset_id=None).all()
    paginator=Paginator(new_server,settings.WEB_PEER_PAGE)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果page不是一个整数，则展示第一页。
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果page不在范围内（例如，9999），则展示结果的最后一页。
        contacts = paginator.page(paginator.num_pages)
    obj=addAssetMD()
    if request.method =='GET':
        return render(request,'new_asset.html',{'all_asset':contacts,
                                            'asset_url':asset_url_list,
                                            'new_asset_count':new_server.count(),
                                            'obj':obj,
                                            })
    elif request.method == 'POST':
        if request.POST.get('server_id'):
            Server_id=request.POST.get('server_id')
            hostname=models.Server.objects.filter(id=Server_id).last().hostname
            return HttpResponse(hostname)
        else:
            obj=addAssetMD(request.POST)
            if obj.is_valid():
                obj.save()
                Asset_obj=models.Asset.objects.all().last()

                models.Asset_status.objects.create(asset=models.Asset.objects.last(),asset_status=0) #设置为在线状态

                models.Audit_log.objects.create(user=request.user,content='将ip地址为:%s的资产入库！！'%models.Server.objects.filter(id=Server_id).first().manage_ipv4)

                models.Server.objects.filter(id=Server_id).update(asset_id=Asset_obj.id)
                return redirect('/new_asset/')
            else:
                print(Server_id)
                print('error data',obj.data)
                print(obj.errors)
                return render(request,'new_asset.html',{'all_asset':contacts,
                                                    'asset_url':asset_url_list,
                                                    'new_asset_count':new_server.count(),
                                                    'Server_id':Server_id,
                                                    'obj':obj,
                                                    'save_asset':'true' #如果为True表示只显示资产入库信息填写界面
                                                    })
    elif request.method=='DELETE':
        delete=QueryDict(request.body)
        server_id=delete.get('server_id')
        obj=models.Server.objects.filter(id=server_id).first()
        models.Audit_log.objects.create(user=request.user,content='将ip地址为:%s的资产设为非法资产！！'%obj.manage_ipv4)

        models.Discard_server(hostname=obj.hostname,
                       sn=obj.sn,
                       manage_ipv4=obj.manage_ipv4,
                        manufacturer=obj.manufacturer,
                        model=obj.model,
                        os_platform=obj.os_platform,
                        create_at=obj.create_at,
                        cpu_physical_count=obj.cpu_physical_count,
                        cpu_model=obj.cpu_model,
                        cpu_count=obj.cpu_count,
                       os_version=obj.os_version,
                       manage_ipv6=obj.manage_ipv6
                       ).save()
        obj.delete()
        return HttpResponse('666')

def Login(request):

    if request.method == 'GET':
        return render(request,'login.html')
    else:
        username=request.POST.get('username')
        pwd=request.POST.get('pwd')
        user=authenticate(username=username,password=pwd)
        if user:
            login(request,user)
            models.Audit_log.objects.create(user=user,content='用户登录成功！')
            return redirect('/')
        else:
            return render(request,'login.html',{'error':'用户名或密码错误！！'})

@login_required
def Logout(request):
    logout(request)
    return redirect('/login')

def api(request):
    if request.method == 'POST':
        asset_data=json.loads(str(request.body,encoding='utf-8'))
        for item in asset_data['system_info']:
            #如果客户端存在于非法资产数据库就直接抛弃
            discard_asset=models.Discard_server.objects.all()
            for name in discard_asset:
                if item['Serial Number'] == name.sn or item['inet'] == name.manage_ipv4 or item['hostname'] == name.hostname:
                    print('非法资产---------')
                    return HttpResponse('非法资产，请联系管理员！')
            def insert_asset(item):

                tmp={
                    'hostname':item['hostname'],
                    'sn':item['Serial Number'],
                    'manufacturer':item['Manufacturer'],
                    'model':item['Product Name'],
                    'manage_ipv4':item.get('inet'),
                    'manage_ipv6':item.get('ipv6'),
                    'os_platform':item['os_platform'],
                    'os_version':item['os_version'],
                    'cpu_count':item['cores'],
                    'cpu_physical_count':item['physical_cpu'],
                    'cpu_model':item['mode']
                }
                server_obj=models.Server.objects.create(**tmp)

                for item in asset_data['disk_info']:
                    for disk_name,disk_size in item.items():
                        models.Disk.objects.create(**{'name':disk_name,'size':disk_size,'server':server_obj})

                for item in asset_data['mem_info']:
                    models.Memory.objects.create(**{'size':item['size'],'speed':item['speed'],'sn':item['sn'],'server':server_obj})

                for item in asset_data['nic_info']:
                    models.Nic.objects.create(**{'name':item['name'],'speed':item['speed'],'mac':item['mac_addr'],'server':server_obj})
                print('新增资产')
                models.asset_change_log.objects.create(log_level=0,server=server_obj,change_detail='客户端第一次上报资产数据，资产摘要：cpu：%s，序列号:%s，型号：%s,管理地址：%s'\
                                                       %(tmp['cpu_model'],tmp['sn'],tmp['manufacturer'],tmp['manage_ipv4']))

                return HttpResponse('新资产已成功录入CMDB数据库') ##
            def update_asset(item,asset_obj,server_obj):
                models.Asset_status.objects.filter(asset=asset_obj,asset_status=1).update(asset_status=0)  #设置为在线状态
                flag=True #资产是否发生变化，如果发生变化flag=False
             #如果数据库中已存在信息，证明不是新资产,更新变化的内容
                updateed_asset={}

                old_asset=server_obj
                if item['Manufacturer'] != old_asset.manufacturer:
                    updateed_asset['manufacturer']=item['Manufacturer']
                if item['Product Name'] !=old_asset.model:
                    updateed_asset['model']=item['Product Name']
                if item['hostname'] !=old_asset.hostname:
                    updateed_asset['hostname']=item['hostname']
                if item['os_platform'] !=old_asset.os_platform:
                    updateed_asset['os_platform']=item['os_platform']
                if item['os_version'] !=old_asset.os_version:
                    updateed_asset['os_version']=item['os_version']
                if item['physical_cpu'] !=str(old_asset.cpu_physical_count):
                    updateed_asset['cpu_physical_count']=item['physical_cpu']
                if item['cores'] !=str(old_asset.cpu_count):
                    updateed_asset['cpu_count']=item['cores']
                if item['mode'] !=old_asset.cpu_model:
                    updateed_asset['cpu_model']=item['mode']
                if item.get('inet') !=old_asset.manage_ipv4:
                    updateed_asset['manage_ipv4']=item['inet']
                if item.get('ipv6') !=old_asset.manage_ipv6:
                    updateed_asset['manage_ipv6']=item['ipv6']
                if len(updateed_asset) !=0:
                    flag=False
                    print('资产信息已更新',updateed_asset)
                    models.Server.objects.filter(sn=item['Serial Number']).update(**updateed_asset)
                    models.asset_change_log.objects.create(log_level=1,server=old_asset,change_detail='系统信息被更新，更新详细：%s'%updateed_asset)
                    if 'cpu_model' in updateed_asset:#如果cpu变化记录日志硬件变更，否则为硬件更新（日志等级不同，决定告警级别）
                        models.Asset_status.objects.create(asset=asset_obj,asset_status=3,type=0,content='系统信息被更新，更新详细：%s'%updateed_asset)
                    else:
                        models.Asset_status.objects.create(asset=asset_obj,asset_status=2,content='系统信息被更新，更新详细：%s'%updateed_asset)

                #比较硬盘资产：
                old_disk=set()
                new_disk=set()
                nice_new_disk={}#将新穿过来的硬盘资产合并成一个字典，方便后面数据处理
                nice_old_disk={}
                for old_disk_item in old_asset.disk_set.all():
                    old_disk.add(old_disk_item.name)
                    nice_old_disk[old_disk_item.name]=old_disk_item.size
                for disk_item in asset_data['disk_info']:
                    for k,v in disk_item.items():
                        new_disk.add(k)
                        nice_new_disk[k]=v
                new_disk_asset=new_disk -old_disk
                if new_disk_asset:#新增硬盘
                    for i in new_disk_asset:
                        print('新增硬盘',i)
                        models.Asset_status.objects.create(asset=asset_obj,asset_status=2,content='新增硬盘%s,容量为：%s'%(i,nice_new_disk[i]))
                        models.asset_change_log.objects.create(log_level=0,server=old_asset,change_detail='新增硬盘%s,容量为：%s'%(i,nice_new_disk[i]))
                        flag=False
                        old_asset.disk_set.create(**{'name':i,'size':nice_new_disk[i]})
                lose_disk=old_disk - new_disk
                if lose_disk:#资产丢失
                    for i in lose_disk:
                        flag=False
                        print('硬盘',i,'丢失')
                        disk_id=models.Disk.objects.filter(server=server_obj,name=i).first().id
                        models.Asset_status.objects.create(asset=asset_obj,asset_status=3,type=1,r_id=disk_id,content='硬盘%s被移除！！,容量为%s'%(i,nice_old_disk[i]))
                        models.asset_change_log.objects.create(log_level=1,server=old_asset,change_detail='硬盘%s被移除！！,容量为%s'%(i,nice_old_disk[i]))
                #比较硬盘size是否改变
                for name,size in nice_old_disk.items():
                    if name in lose_disk: #如果硬盘已经被移除了，就不再比较容量是否发生变化
                        continue
                    if nice_new_disk.get(name) != size:
                        flag=False
                        print('硬盘容量发生变化：',name)
                        print('new_size',nice_new_disk[name])
                        disk_id=models.Disk.objects.filter(server=server_obj,name=name).first().id
                        models.Asset_status.objects.create(asset=asset_obj,asset_status=3,type=1,r_id=disk_id,action=0,content='硬盘%s容量从%s变为%s！！'%(name,size,nice_new_disk[name]))
                        models.asset_change_log.objects.create(log_level=1,server=old_asset,change_detail='硬盘%s容量从%s变为%s！！'%(name,size,nice_new_disk[name]))
                        old_asset.disk_set.filter(name=name).update(**{'size':nice_new_disk[name]})
                #比较内存资产:
                old_mem=set()
                new_mem=set()
                for mem_item in asset_data['mem_info']:
                    new_mem.add(mem_item['sn'])
                for mem_obj in  old_asset.memory_set.all():
                    old_mem.add(mem_obj.sn)
                add_mem=new_mem - old_mem
                if add_mem:#增加新内存条
                    for mem_item in asset_data['mem_info']:
                        if mem_item['sn'] in add_mem:
                            flag=False
                            print('增加新内存条',mem_item['size'])
                            print(old_asset)
                            models.Asset_status.objects.create(asset=asset_obj,asset_status=2,content='增加容量为%s的新内存条！！'%mem_item['size'])
                            models.asset_change_log.objects.create(log_level=0,server=old_asset,change_detail='增加容量为%s的新内存条！！'%mem_item['size'])
                            old_asset.memory_set.create(**{
                                'size':mem_item['size'],
                                'speed':mem_item['speed'],
                                'sn':mem_item['sn']
                            })
                lose_mem=old_mem-new_mem
                if lose_mem:#内存条丢失
                    flag=False
                    print('内存条丢失',lose_mem)
                    lose_mem_size=models.Memory.objects.filter(server=old_asset).first().size
                    for Lose_mem in lose_mem:
                        mem_id=models.Memory.objects.filter(server=server_obj,sn=Lose_mem).first().id
                        models.Asset_status.objects.create(asset=asset_obj,asset_status=3,type=2,r_id=mem_id,content='内存条丢失,SN:%s,容量:%s！！'%(lose_mem,lose_mem_size))
                        models.asset_change_log.objects.create(log_level=1,server=old_asset,change_detail='内存条丢失,SN:%s,容量:%s！！'%(lose_mem,lose_mem_size))

                #比较网卡是否发生变化
                old_nic=set()
                new_nic=set()

                for nic_item in asset_data['nic_info']:
                    new_nic.add(nic_item['mac_addr'])
                for nic_obj in  old_asset.nic_set.all():
                    old_nic.add(nic_obj.mac)

                add_nic=new_nic - old_nic
                if add_nic:#增加新网卡
                    for nic_item in asset_data['nic_info']:
                        if nic_item['mac_addr'] in add_nic:
                            flag=False
                            print('增加新网卡',nic_item['mac_addr'])
                            models.Asset_status.objects.create(asset=asset_obj,asset_status=2,content='增加新网卡,mac地址为:%s！！'%nic_item['mac_addr'])
                            models.asset_change_log.objects.create(log_level=0,server=old_asset,change_detail='增加新网卡,mac地址为:%s！！'%nic_item['mac_addr'])
                            old_asset.nic_set.create(**{
                                'name':nic_item['name'],
                                'speed':nic_item['speed'],
                                'mac':nic_item['mac_addr']
                            })
                lose_nic=old_nic-new_nic
                if lose_nic:#网卡丢失
                    flag=False
                    for Nic in lose_nic:
                        print('网卡丢失',Nic)
                        nic_id=models.Nic.objects.filter(server=server_obj,mac=Nic).first().id
                        models.Asset_status.objects.create(asset=asset_obj,asset_status=3,type=3,r_id=nic_id,content='网卡%s被移除！！'%lose_nic)
                        models.asset_change_log.objects.create(log_level=1,server=old_asset,change_detail='网卡%s被移除！！'%lose_nic)


                if flag:
                    print('客户端上报资产成功，资产未发生变化')

                return HttpResponse('资产变更信息已经修改到cmdb数据库')

            #处理有些服务器获取到错误的序列号时将ip作为唯一标识
            if re.search('filled',item['Serial Number']):
                res='Unknow'
            else:
                res=models.Server.objects.filter(sn=item['Serial Number']).first()

            import datetime
            if res == 'Unknow': #该主机无法获取到SN，此时采用主机名做唯一标识符{部分组装机无法获取到SN}
                res=models.Server.objects.filter(hostname=item['hostname']).first()
                if res:
                    models.Asset.objects.filter(server=res).update(report_time=datetime.datetime.now()) #更新汇报时间,用于判断客户端是否离线
                    asset_obj=models.Asset.objects.filter(server=res).first()
                    try:
                        response=update_asset(item,asset_obj,res)
                        return response
                    except Exception as e:
                        print('客户端%s更新资产数据出现错误%s'%(item['hostname'],e))
                        return HttpResponse('%s STATUS ERROR'%item['hostname'])
                else:
                    try:
                        response=insert_asset(item)
                        return response
                    except Exception as e:
                        print('客户端%s上报资产数据出现错误%s'%(item['hostname'],e))
                        return HttpResponse('%s STATUS ERROR'%item['hostname'])
            else:
                if res:
                    asset_obj=models.Asset.objects.filter(server=res).first()
                    models.Asset.objects.filter(server=res).update(report_time=datetime.datetime.now()) #更新汇报时间,用于判断客户端是否离线
                    try:
                        response=update_asset(item,asset_obj,res)
                        return response
                    except Exception as e:
                        print('客户端%s上报资产数据出现错误%s'%(item['hostname'],e))
                        return HttpResponse('%s STATUS ERROR'%item['hostname'])
                else:
                    try:
                        response=insert_asset(item)
                        return response
                    except Exception as e:
                        print('客户端%s上报资产数据出现错误%s'%(item['hostname'],e))
                        return HttpResponse('%s STATUS ERROR'%item['hostname'])
@login_required
def audit_log(request):
    if request.GET.get('user_name'):
        audit_log_obj=models.Audit_log.objects.filter(user__email=request.GET.get('user_name')).order_by('-date')
    else:
        audit_log_obj=models.Audit_log.objects.all().order_by('-date')
    paginator=Paginator(audit_log_obj,settings.WEB_PEER_PAGE)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # 如果page不是一个整数，则展示第一页。
        contacts = paginator.page(1)
    except EmptyPage:
        # 如果page不在范围内（例如，9999），则展示结果的最后一页。
        contacts = paginator.page(paginator.num_pages)

    return render(request,'audit_log.html',{'log_obj':contacts})

@login_required
def notepad(request):
    if request.method=='DELETE':
        Nt_id=QueryDict(request.body).get('Nt_id')
        models.Notepad.objects.filter(id=Nt_id).delete()
        return HttpResponse('666')
    if request.method=='POST':
        title=request.POST.get('title')
        content=request.POST.get('content')
        models.Notepad.objects.create(user=request.user,title=title,content=content)
        return redirect('/notepad/')
    all_notepad_obj=models.Notepad.objects.all().order_by('-date')
    return render(request,'notepad.html',{'notepad_obj':all_notepad_obj})